package com.miyuan.wm.utils;

import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;

/**
 * @Description 网络工具类
 * @return:
 * @author:张龙飞
 * @date:2020/12/3 16:57
 */
public class NetworkUtil {

	/**
     * 获取本机IP配置信息
     */
    public static String currentIp() {
    	String ipresult = "";
        try {
			// 获取网卡和网桥映射关系
			Enumeration<NetworkInterface> nativeNetworks = NetworkInterface.getNetworkInterfaces();
			while (nativeNetworks.hasMoreElements()) {
			    NetworkInterface networkCard = (NetworkInterface) nativeNetworks.nextElement();
			    String cardeName = networkCard.getName();
			    if (cardeName.contains("eth") || cardeName.contains("br")) {// 判断是否是本地网卡
			        List<InterfaceAddress> ncAddrList = networkCard.getInterfaceAddresses();
			        Iterator<InterfaceAddress> ncAddrIterator = ncAddrList.iterator();
			        // 计算iP及子网掩码
			        while (ncAddrIterator.hasNext()) {
			            InterfaceAddress networkCardAddress = ncAddrIterator.next();
			            InetAddress address = networkCardAddress.getAddress();
			            if (!address.isLoopbackAddress()) {
			                String ip = address.getHostAddress();
			                if (ip.indexOf(":") <= 0) {
			                	ipresult = ip;
			                }
			            }
			        }
			    }
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
        return ipresult;
    }

}
